package token

import (
	"chatgpt/helper"
	"chatgpt/model/system"
	"chatgpt/services/datasrv"
	"chatgpt/services/datasrv/sqlhelper"
	"context"
	mcache "github.com/patrickmn/go-cache"
	"github.com/slclub/glog"
	"time"
)

var Login LoginSrv

type LoginSrv struct {
	Cache *mcache.Cache
}

func (self *LoginSrv) GetUserGpt(key string) *system.UserGpt {
	glog.Debugf("TOKEN.USER.CHECK %v", key)
	if key == helper.Config().Sub("Server").GetString("AuthToken") {
		return &system.UserGpt{
			Account: "chatgpt",
		}
	}
	//ugpt := self.GetUserGptFromCache(key)
	//if ugpt != nil {
	//	return ugpt
	//}
	return nil //self.GetUserGptFromDB(key)
}

func (self *LoginSrv) GetUserGptFromDB(key string) *system.UserGpt {
	req := sqlhelper.ReqWhere{
		Where: &sqlhelper.Where{
			Conds: []*sqlhelper.CondItem{sqlhelper.WhereCond("ApiKey", key)},
		},
	}
	res := sqlhelper.ResWhere{}

	datasrv.SystemSrv.UserGptFirst(context.Background(), &req, &res)
	data, ok := res.Data.(map[string]any)
	defer glog.Infof("DataSrv.UserGpt.First key:%v code:%v account:%v", key, res.MsgCode, data["ApiKey"])
	if !ok {
		return nil
	}
	obj := &system.UserGpt{}
	obj.ConvFromMap(data)
	self.Cache.Set(key, obj, time.Hour)
	return obj
}

func (self *LoginSrv) GetUserGptFromCache(key string) *system.UserGpt {
	usr, ok := self.Cache.Get(key)
	if !ok {
		return nil
	}

	gptu, ok := usr.(*system.UserGpt)
	if !ok {
		return nil
	}
	return gptu
}
